package cn.edu.ctbu.lablist.webapi;

import cn.edu.ctbu.lablist.core.PageUtils;
import cn.edu.ctbu.lablist.domain.Student;
import cn.edu.ctbu.lablist.service.StudentService;
import cn.edu.ctbu.lablist.utils.RUtil;
import cn.edu.ctbu.lablist.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    private StudentService studentService;

    /**
     * 读取的url:/webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public R<List<Student>> getAll(){
        List<Student> students = studentService.findAll();
        return RUtil.success(students);
    }

    @GetMapping("/validateUser")
    public R validateNoAndPassword(String no,String password) throws Exception{
        return RUtil.success(studentService.validateUsernameAndPassword(no,password));
    }

    @GetMapping("/list2")
    public R<Page<Student>> list(int pageIndex, int pageSize){
        Pageable pageable = PageRequest.of(pageIndex,pageSize,Sort.by("id").ascending());
        return RUtil.success(studentService.findAll(pageable));
    }

    /**
     * 读取的url:/webapi/student/get/id
     * @return
     */
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Long id){
        Student student = studentService.getById(id);
        student.setPassword("");
        return student;
    }

    /**
     * 新增学生的方法,/webapi/student/delete
     * @param name
     * @return
     */
    @GetMapping("/findname")
    public R<List<Student>> find(String name){
        List<Student> students = studentService.findByName(name);
        return RUtil.success(students);
    }
    @GetMapping("/findno")
    public R<List<Student>> findno(String no){
        List<Student> students = studentService.findByNo(no);
        return RUtil.success(students);
    }
    /**
     * 新增学生的方法,/webapi/student/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public R insert(@Valid Student student, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生出错了!{}",errorMsg);
            return RUtil.error(-10,errorMsg);
        }
        studentService.insert(student);
        Long myid = Long.valueOf(student.getId());

        return RUtil.success(myid.intValue());
    }
    /**
     * 更新学生的方法,/webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public R<Student> update(Student student){
        //读取旧数据
        Student oldstudent=studentService.getById(Long.valueOf(student.getId()));

        if (StringUtils.isEmpty(student.getPassword())){
            //没有新密码,那么就是旧密码
            student.setPassword(oldstudent.getPassword());
        }
        student = studentService.update(student);
        return RUtil.success(student);

    }

    /**
     * 新增学生的方法,/webapi/student/delete
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Long id){
        studentService.delete(id);
    }


    /**
     * 分页，读取全部内容
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "name",defaultValue = "") String name){
        //按id排倒序
        Sort sort=Sort.by(Sort.Direction.ASC,"id");
        Page<Student> studentPage;
        if(StringUtils.isEmpty(name)){
            Pageable pageable = PageRequest.of(page,size,sort);
            studentPage = studentService.findAll(pageable);
        }
        else{
            Student student = new Student();
            student.setName(name);
            Pageable pageable = PageRequest.of(0,10,sort);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student> example = Example.of(student,matcher);
            studentPage = studentService.findAll(example,pageable);
        }
        PageUtils pageUtils = new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }

    @PostMapping("/add")
    public R add(@Valid Student student, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生出错了!{}", errorMsg);
            return RUtil.error(-10, errorMsg);
        }
        studentService.add(student);
        Long myid = Long.valueOf(student.getId());

        return RUtil.success(myid.intValue());
    }
}
